package com.caogen.cg_wl_kt.utils

import android.content.Context
import android.content.SharedPreferences

/**
 * 项目名称: cg_wl_kt
 * Packages:com.caogen.cg_wl_kt.utils
 * author: FSW
 * 创建日期: 2024/2/26 17:30
 * Describe:
 *
 */
 object PrefUtils {
    // 配置文件名称
    private val PREFERENCE_NAME = "yudi_pref"

    val LOGIN_TOKEN = "login_token"

    val USER_NAME = "user_name"

    val RESULT_NAME = "result_name"

    fun put(context: Context, key: String?, `object`: Any): Boolean {
        val type = `object`.javaClass.simpleName
        val editor: SharedPreferences.Editor = getEditor(context)
        if ("String" == type) {
            editor.putString(key, `object` as String)
        } else if ("Integer" == type) {
            editor.putInt(key, (`object` as Int))
        } else if ("Boolean" == type) {
            editor.putBoolean(key, (`object` as Boolean))
        } else if ("Float" == type) {
            editor.putFloat(key, (`object` as Float))
        } else if ("Long" == type) {
            editor.putLong(key, (`object` as Long))
        }
        return editor.commit()
    }

    operator fun get(context: Context, key: String?, defaultObject: Any): Any? {
        val type = defaultObject.javaClass.simpleName
        val sp = getSharedPreferences(context)
        if ("String" == type) {
            return sp.getString(key, defaultObject as String)
        } else if ("Integer" == type) {
            return sp.getInt(key, (defaultObject as Int))
        } else if ("Boolean" == type) {
            return sp.getBoolean(key, (defaultObject as Boolean))
        } else if ("Float" == type) {
            return sp.getFloat(key, (defaultObject as Float))
        } else if ("Long" == type) {
            return sp.getLong(key, (defaultObject as Long))
        }
        return null
    }

    fun remove(context: Context, key: String?): Boolean {
        val editor = getEditor(context)
        return editor.remove(key).commit()
    }

    fun clear(context: Context): Boolean {
        val editor = getEditor(context)
        return editor.clear().commit()
    }

    private fun getEditor(context: Context): SharedPreferences.Editor {
        return getSharedPreferences(context).edit()
    }

    private fun getSharedPreferences(context: Context): SharedPreferences {
        return context.getSharedPreferences(
            PREFERENCE_NAME,
            Context.MODE_PRIVATE
        )
    }
}